using System.Collections.Generic;
using System.Linq;
using Irony.Ast;
using Irony.Parsing;

namespace Flit
{
    ///<summary>
    /// A label attribute's value. Represents a name and a list of parameters. <example>foo(int bar)</example>
    ///</summary>
    public class Label : IAstNodeInit
    {
        ///<summary>
        /// Construct a Label
        ///</summary>
        public Label()
        {
            Parameters = Enumerable.Empty<Parameter>();
        }

        /// <summary>
        /// Called by Irony
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parseNode"></param>
        public void Init(ParsingContext context, ParseTreeNode parseNode)
        {
            Name = parseNode.DescendantsWithTermType(x => x.Identifier).First().Token.ValueString;

            var parameters = parseNode.DescendantsWithTermType(x => x.ParameterList).SingleOrDefault();
            if (parameters != null)
            {
                Parameters = parameters.ChildNodes
                    .Select(c => new Parameter(
                                    c.ChildNodes[0].Token.ValueString, 
                                    c.ChildNodes[1].Token.ValueString
                                 ))
                    .ToList();

            }
        }

        /// <summary>
        /// What was this label called <example><b>foo</b>(int bar)</example>
        /// </summary>
        public string Name { get; internal set; }

        /// <summary>
        /// What was this label's parameters <example>foo(<b>int bar</b>)</example>
        /// </summary>
        public IEnumerable<Parameter> Parameters { get; internal set; }

        /// <summary>
        /// Reprint this label's parameters as a method definition
        /// </summary>
        public string ParametersAsFormalMethodDefinition
        {
            get
            {
                var v = Parameters.Select(x => x.AsParameterDeclaration).ToArray();
                return string.Join(", ", v);
            }
        }

        /// <summary>
        /// Reprint this label's parameters as a method call (ie no data types, just parameter names)
        /// </summary>
        public string ParametersAsMethodCall
        {
            get
            {
                var v = Parameters.Select(x => x.Name).ToArray();
                return string.Join(", ", v);
            }
        }
    }
}